// 实现这个项目的构建任务

// 引入gulp的相关API
const { src,dest,parallel,series,watch }  = require('gulp')

const browserSync = require('browser-sync')
const del = require('del')

// 自动加载gulp插件
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()

// 模板编译数据
const data = {
    menus:[
        {
            name: 'Home',
            icon: 'aperture',
            link:'index.html'
        },
        {
            name:'About',
            link: 'about.html'
        },
        {
            name: 'Contact',
            link:'#',
            children: [
                {
                    name: 'Twitter',
                    link:'https://twitter.com/w_zce'
                } 
            ]
        }
    ],
    pkg:require('./package.json'),
    date: new Date()
}

// 编译sass文件
const style = () => {
    return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))
}

// 编译js文件
const script = () => {
    return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
}

// 编译模板文件
const page = () => {
    return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ data }))
    .pipe(dest('temp'))
}

// 图片压缩
const image = () => {
    return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))

}

// svg压缩
const font = () => {
    return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))

}

//其他文件
const extra = () => {
    return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}



// 删除文件
const clean = () => {
     return del(['dist','temp'])
}

// 测试服务器
const serve = () => {
    // 监听文件改动自动编译
    watch('src/assets/styles/*.scss',style)
    watch('src/assets/scripts/*.js',script)
    watch('src/*.html',page)
    watch(['src/assets/images/**','src/assets/fonts/**','public/**'],browserSync.reload)

    browserSync.init({
        files: 'temp/**',
        server: {
            baseDir: ['temp','src','public'],
            routes: {
                '/node_modules':'node_modules'
            }
        }
    })
}

//useref
const useref = () => {
    return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({searchPath:['temp','.']}))
    .pipe(plugins.if(/\.js$/,plugins.uglify()))
    .pipe(plugins.if(/\.css$/,plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/,plugins.htmlmin({
         collapseWhitespace: true,
         minifyCSS: true,
         minifyJS: true
     })))
    .pipe(dest('dist'))
}

// 组合编译任务
const compile = parallel(style,script,page)

const build =  series(clean,parallel(series(compile,useref),image,font,extra)) 

const dev = series(compile,serve)

module.exports = {
    build,
    dev
}
